package com.zhw;


import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;

/**
 * @author weizhang52
 * @description: MongodbClient根据数据库的URL地址和数据端口号连接后，通过指定数据库名称获得操作数据库的对象，
 * 通过设定集合名称返回操作集合的对象，对集合进行查询操作。
 * @date 2019/7/1
 * @modify
 */
public class MongodbClient {

    public static MongoClient mongoClient = null;
    public MongoDatabase database = null;
    public MongoCollection<Document> collection = null;
    public FindIterable<Document> findIterable = null;
    public MongoCursor<Document> mongoCursor = null;

    /**
     * 不通过认证获取连接数据库对象
     *
     * @param host   数据库ip地址
     * @param port   端口
     * @param dbName 数据库名称
     * @return
     */
    public static MongoDatabase getConnect(String host, int port, String dbName) {

        // 连接到 mongodb 服务
        MongoClient mongoClient = new MongoClient(host, port);
        // 连接到数据库
        MongoDatabase mongoDatabase = mongoClient.getDatabase(dbName);
        // 返回连接数据库对象
        return mongoDatabase;

    }

    /**
     * 关闭数据库连接
     */
    public static void closeConnection() {

        if (mongoClient != null) {
            mongoClient.close();
        }

    }

//    public void ConnectionMongoClient(String host, int port, String databaseName) {
//        try {
//            mongoClient = new MongoClient(host, port);
//            database = mongoClient.getDatabase(databaseName);
//            System.out.println("Connection Successfully !");
//
//        } catch (Exception e) {
//            System.out.println("Mongodb Connection Exception:");
//            e.printStackTrace();
//        }
//    }
//
//    public MongoCursor query(String collectionName, String queryStr) {
//        collection =  database.getCollection(collectionName);
//        findIterable =  (FindIterable<Document>) collection.find();
//        mongoCursor = findIterable.iterator();
//        System.out.print("Query Successfully !");
//        String str = "";
//        return mongoCursor;
//
//    }
//
//    public void closeConnection() {
//        if (mongoClient != null) {
//            mongoClient.close();
//        }
//    }

}
